<template>
  <view class="activity-detail-container">
   

    <!-- 详情查看模式 -->
    <view v-if="mode === 'view'" class="detail-content">
      <view class="detail-section">
        <view class="detail-item">
          <text class="detail-label">标题：</text>
          <text class="detail-value">{{ activityData.title }}</text>
        </view>
        
        <view class="detail-item">
          <text class="detail-label">发布人：</text>
          <text class="detail-value">{{ activityData.publisher }}</text>
        </view>
        
        <view class="detail-item">
          <text class="detail-label">发布时间：</text>
          <text class="detail-value">{{ activityData.publishTime }}</text>
        </view>
        
        <view class="detail-item">
          <text class="detail-label">审核状态：</text>
          <text class="detail-value" :class="['review-status', getReviewStatusClass(activityData.reviewStatus)]">
            {{ activityData.reviewStatus }}
          </text>
        </view>
        
        <view class="detail-item">
          <text class="detail-label">审核时间：</text>
          <text class="detail-value">{{ activityData.reviewTime }}</text>
        </view>
        
        <view class="detail-item detail-note">
          <text class="detail-label">审核说明：</text>
          <text class="detail-value">{{ activityData.reviewNote }}</text>
        </view>
        
        <view class="detail-item">
          <text class="detail-label">发布内容：</text>
          <text class="detail-value content-text">{{ activityData.content }}</text>
        </view>
      </view>
      
      
    </view>

    <!-- 发布模式 -->
    <view v-else-if="mode === 'publish'" class="publish-content">
      <view class="form-section">
        <view class="form-item">
          <text class="form-label">标题:</text>
          <input 
            v-model="publishForm.title" 
            type="text" 
            placeholder="请输入活动标题"
            class="form-input"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">内容:</text>
          <textarea 
            v-model="publishForm.content" 
            placeholder="活动内容"
            class="form-textarea"
          ></textarea>
        </view>
        
        
      </view>
      
      <view class="publish-btn-container">
        <button class="publish-button" @tap="submitPublish">发布</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';

// 模式：view - 查看详情，publish - 发布活动
const mode = ref<'view' | 'publish'>('view');
const activityId = ref<string>('');

// 页面标题
const pageTitle = computed(() => {
  return mode.value === 'view' ? '活动详情' : '发布活动';
});

// 活动详情数据
const activityData = ref({
  id: '',
  title: '阳春三月油江南活动开始报名了',
  publisher: 'XX广播',
  publishTime: '2022/10/10 11:09',
  reviewStatus: '待审核/审核通过/审核不通过',
  reviewTime: '2022/10/10 11:09',
  reviewNote: '审核内容审核内容审核内容审核内容审核内容审核内容审核内容',
  content: '活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容活动内容',
  imageUrl: ''
});

// 发布表单数据
const publishForm = ref({
  title: '',
  content: '活动内容',
  imageUrl: ''
});

// 获取审核状态对应的样式类
const getReviewStatusClass = (status: string): string => {
  if (status.includes('待审核')) return 'status-pending';
  if (status.includes('通过')) return 'status-approved';
  if (status.includes('不通过') || status.includes('失败')) return 'status-rejected';
  return '';
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 选择图片
const selectImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      if (res.tempFilePaths && res.tempFilePaths.length > 0) {
        publishForm.value.imageUrl = res.tempFilePaths[0];
      }
    }
  });
};

// 移除图片
const removeImage = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        publishForm.value.imageUrl = '';
      }
    }
  });
};

// 提交发布
const submitPublish = async () => {
  // 简单的表单验证
  if (!publishForm.value.title.trim()) {
    uni.showToast({
      title: '请输入活动标题',
      icon: 'none'
    });
    return;
  }
  
  if (!publishForm.value.content.trim()) {
    uni.showToast({
      title: '请输入活动内容',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载提示
  uni.showLoading({
    title: '发布中...'
  });
  
  try {
    // 获取当前时间
    const currentTime = new Date().toISOString();
    
    // 调用真实API接口
    const response = await uni.request({
      url: 'http://localhost:8080/cc/activity',
      method: 'POST',
      data: {
        title: publishForm.value.title,
        content: publishForm.value.content,
        time: currentTime
      }
    });
    
    uni.hideLoading();
    
    // 检查响应状态
    if (response.statusCode === 200) {
      uni.showToast({
        title: '发布成功',
        icon: 'success'
      });
      
      // 发布成功后返回列表页
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/activity/list'
        });
      }, 1500);
    } else {
      uni.showToast({
        title: '发布失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
    console.error('发布活动失败:', error);
  }
};

// 加载活动详情
const loadActivityDetail = (id: string, detailData?: any) => {
  console.log('开始加载活动详情，ID:', id);
  
  // 如果已经有从URL传递的详情数据，则直接使用
  if (detailData) {
    console.log('使用URL参数传递的活动详情数据', detailData);
    
    // 检查数据结构，处理嵌套的data字段（从日志中看到实际数据结构是 {code, data, msg}）
    const actualData = detailData.data || detailData;
    console.log('实际使用的数据:', actualData);
    
    // 将API返回的数据映射到activityData结构，确保与模板中使用的字段匹配
    activityData.value = {
      id: actualData.id || '',
      title: actualData.title || '无标题',
      publisher: actualData.merchantName || '未知发布者', // 映射merchantName到publisher
      publishTime: actualData.time ? formatDateTime(actualData.time) : (actualData.updateTime ? formatDateTime(actualData.updateTime) : '未知时间'), // 优先使用time，其次updateTime
      reviewStatus: getReviewStatusText(actualData.status), // 映射status到reviewStatus文本
      reviewTime: actualData.updateTime ? formatDateTime(actualData.updateTime) : '', // 使用updateTime作为审核时间
      reviewNote: actualData.remark || actualData.extend1 || '暂无审核说明', // 优先使用remark，其次extend1
      content: actualData.content || '无内容',
      imageUrl: actualData.imageUrl || ''
    };
    console.log('映射后的活动数据:', activityData.value);
    return;
  }
  
  // 如果没有URL参数数据，则显示加载状态并使用模拟数据
  uni.showLoading({
    title: '加载中...'
  });
  
  setTimeout(() => {
    uni.hideLoading();
    console.log('没有获取到详情数据，使用默认数据');
    // 设置默认数据，确保页面能正常显示
    activityData.value = {
      id: '',
      title: '默认活动标题',
      publisher: '默认发布者',
      publishTime: '未知时间',
      reviewStatus: '待审核',
      reviewTime: '',
      reviewNote: '暂无审核说明',
      content: '暂无活动内容',
      imageUrl: ''
    };
  }, 500);
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string): string => {
  if (!dateTimeStr) return '';
  
  try {
    const date = new Date(dateTimeStr);
    // 检查是否为有效日期
    if (isNaN(date.getTime())) return dateTimeStr;
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}/${month}/${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateTimeStr;
  }
};

// 获取审核状态文本
const getReviewStatusText = (status: number | undefined): string => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '审核通过',
    2: '审核不通过'
  };
  
  return status !== undefined ? statusMap[status] || '未知状态' : '待审核';
};

// 页面加载时初始化
onMounted(() => {
  // 获取路由参数 - 使用uni-app正确的方式
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1] as any;
  const routeMode = currentPage.options?.mode as string;
  const routeId = currentPage.options?.id as string;
  const routeData = currentPage.options?.data as string;
  
  if (routeMode === 'publish') {
    mode.value = 'publish';
  } else {
    mode.value = 'view';
    if (routeId) {
      activityId.value = routeId;
      
      // 尝试解析URL参数中的data数据
      let detailData: any = undefined;
      if (routeData) {
        try {
          detailData = JSON.parse(decodeURIComponent(routeData));
          console.log('成功解析URL中的活动详情数据:', detailData);
        } catch (error) {
          console.error('解析URL数据失败:', error);
        }
      }
      
      // 调用加载详情函数，传入ID和可能的详情数据
      loadActivityDetail(routeId, detailData);
    }
  }
});
</script>

<style scoped>
.activity-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏样式 */
.navbar {
  display: flex;
  align-items: center;
  height: 100rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #eaeaea;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left,
.nav-right {
  width: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}

.back-icon {
  font-size: 44rpx;
  color: #333333;
}

/* 详情内容样式 */
.detail-content {
  padding: 30rpx;
}

.detail-section {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: flex-start;
}

.detail-item.detail-note {
  margin-bottom: 30rpx;
}

.detail-label {
  width: 200rpx;
  font-size: 32rpx;
  color: #666666;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  font-size: 32rpx;
  color: #333333;
  word-break: break-all;
}

.content-text {
  line-height: 48rpx;
  margin-top: 0;
}

.review-status {
  padding: 2rpx 16rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.status-pending {
  color: #ff9500;
  background-color: #fff0e0;
}

.status-approved {
  color: #4cd964;
  background-color: #e0f7e0;
}

.status-rejected {
  color: #ff3b30;
  background-color: #ffe0e0;
}

/* 图片区域样式 */
.image-section {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
}

.image-container {
  margin-top: 20rpx;
  margin-left: 200rpx;
}

.activity-image {
  width: 400rpx;
  height: 400rpx;
  border-radius: 8rpx;
}

.image-placeholder {
  width: 400rpx;
  height: 400rpx;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999999;
  font-size: 28rpx;
  border-radius: 8rpx;
}

/* 发布表单样式 */
.publish-content {
  padding: 30rpx;
}

.form-section {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 10rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #eaeaea;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  color: #333333;
}

.form-textarea {
  width: 100%;
  height: 300rpx;
  border: 1px solid #eaeaea;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 32rpx;
  color: #333333;
  resize: none;
}

/* 上传区域样式 */
.upload-section {
  margin-top: 10rpx;
}

.upload-preview {
  position: relative;
  width: 400rpx;
  height: 400rpx;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-icon {
  position: absolute;
  top: -20rpx;
  right: -20rpx;
  width: 60rpx;
  height: 60rpx;
  background-color: #ff3b30;
  color: #ffffff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40rpx;
  font-weight: bold;
}

.upload-button {
  width: 400rpx;
  height: 400rpx;
  border: 1px dashed #eaeaea;
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
}

.upload-plus {
  font-size: 64rpx;
  color: #cccccc;
}

/* 发布按钮样式 */
.publish-btn-container {
  margin-top: 50rpx;
  padding: 0 30rpx;
}

.publish-button {
  width: 100%;
  height: 92rpx;
  background-color: #007aff;
  color: #ffffff;
  font-size: 36rpx;
  border-radius: 46rpx;
}
</style>